package beans.jdk7.fork$join;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * RecursiveTask还可以带返回值,这里给出一段代码作为参考
 * 
 * 斐波那契函数
 */
public class Fibonacci extends RecursiveTask<Integer>
{
	private static final long serialVersionUID = 1L;
	final int n;

	public Fibonacci(int n)
	{
		this.n = n;
	}

	private int compute(int small)
	{
		final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
		return results[small];
	}

	@Override
	public Integer compute()
	{
		if (n <= 10)
		{
			return compute(n);
		}

		Fibonacci f1 = new Fibonacci(n - 1);
		Fibonacci f2 = new Fibonacci(n - 2);
		System.out.println("fork new thread for " + (n - 1));
		f1.fork();
		System.out.println("fork new thread for " + (n - 2));
		f2.fork();
		return f1.join() + f2.join();
	}

	public static void main(String[] args)
	{
		Fibonacci f = new Fibonacci(11);
		ForkJoinPool poll = new ForkJoinPool();
		System.out.println(poll.invoke(f));
	}
}
